'use strict';

const Service = require('egg').Service;

class UserService extends Service {

  async findAll() {
    const { ctx } = this;
    return await ctx.model.User.find();
  }

  async findByName(name) {
    const { ctx } = this;
    const result = await ctx.model.User.find({ name: `${name}` });
    return result;
  }

  async findById(id) {
    const { ctx } = this;
    const result = await ctx.model.User.findById(id);
    return result || {};
  }

  /**
   * 添加用户
   * @param {*} user json
   */
  async add(user) {
    const { ctx } = this;
    const u = new ctx.model.User(user);
    return u.save();
  }

  async update(user) {
    const { ctx } = this;
    return await ctx.model.User.updateOne({ _id: user.id }, user);
  }

  async deleteById(id) {
    return this.ctx.model.User.deleteOne({ _id: id });
  }
}

module.exports = UserService;
